package com.lifeverse.controller;

import com.lifeverse.common.ApiResponse;
import com.lifeverse.entity.KnowledgeBase;
import com.lifeverse.entity.LearningExperience;
import com.lifeverse.repository.KnowledgeBaseRepository;
import com.lifeverse.repository.LearningExperienceRepository;
import com.lifeverse.service.LearningAdaptationService;
import com.lifeverse.service.KnowledgeManagementService;
import com.lifeverse.service.ExperienceLearningService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 学习和适应系统控制器
 * 提供学习和适应相关的API接口
 */
@RestController
@RequestMapping("/api/learning-adaptation")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "学习和适应系统", description = "生命体学习和适应系统API")
public class LearningAdaptationController {

    private final LearningAdaptationService learningAdaptationService;
    private final KnowledgeManagementService knowledgeManagementService;
    private final ExperienceLearningService experienceLearningService;
    private final LearningExperienceRepository learningExperienceRepository;
    private final KnowledgeBaseRepository knowledgeBaseRepository;

    /**
     * 执行学习和适应
     */
    @PostMapping("/learn/{lifeEntityId}")
    @Operation(summary = "执行学习和适应", description = "为指定生命体执行完整的学习和适应流程")
    public ResponseEntity<ApiResponse<CompletableFuture<LearningAdaptationService.LearningAdaptationResult>>> performLearning(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "经验数据") @RequestBody Map<String, Object> experienceData) {
        
        log.info("收到学习和适应请求，生命体ID: {}", lifeEntityId);
        
        try {
            CompletableFuture<LearningAdaptationService.LearningAdaptationResult> result = 
                    learningAdaptationService.performLearningAdaptation(lifeEntityId, experienceData);
            
            return ResponseEntity.ok(ApiResponse.success(result));
            
        } catch (Exception e) {
            log.error("学习和适应失败", e);
            return ResponseEntity.ok(ApiResponse.error("学习和适应失败: " + e.getMessage()));
        }
    }

    /**
     * 应用学习成果
     */
    @PostMapping("/apply/{lifeEntityId}")
    @Operation(summary = "应用学习成果", description = "将学习成果应用到新情况")
    public ResponseEntity<ApiResponse<LearningAdaptationService.LearningApplicationResult>> applyLearning(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "情况数据") @RequestBody Map<String, Object> situationData) {
        
        try {
            LearningAdaptationService.LearningApplicationResult result = 
                    learningAdaptationService.applyLearningToSituation(lifeEntityId, situationData);
            
            return ResponseEntity.ok(ApiResponse.success(result));
            
        } catch (Exception e) {
            log.error("应用学习成果失败", e);
            return ResponseEntity.ok(ApiResponse.error("应用学习成果失败: " + e.getMessage()));
        }
    }

    /**
     * 记录学习经验
     */
    @PostMapping("/experience/{lifeEntityId}")
    @Operation(summary = "记录学习经验", description = "为生命体记录新的学习经验")
    public ResponseEntity<ApiResponse<LearningExperience>> recordExperience(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "经验数据") @RequestBody Map<String, Object> experienceData) {
        
        try {
            LearningExperience experience = experienceLearningService
                    .recordLearningExperience(lifeEntityId, experienceData);
            
            return ResponseEntity.ok(ApiResponse.success(experience));
            
        } catch (Exception e) {
            log.error("记录学习经验失败", e);
            return ResponseEntity.ok(ApiResponse.error("记录学习经验失败: " + e.getMessage()));
        }
    }

    /**
     * 获取学习经验
     */
    @GetMapping("/experience/{lifeEntityId}")
    @Operation(summary = "获取学习经验", description = "获取指定生命体的学习经验列表")
    public ResponseEntity<ApiResponse<Page<LearningExperience>>> getExperiences(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size) {
        
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "startedAt"));
            Page<LearningExperience> experiences = learningExperienceRepository.findByLifeEntityId(lifeEntityId, pageable);
            
            return ResponseEntity.ok(ApiResponse.success(experiences));
            
        } catch (Exception e) {
            log.error("获取学习经验失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取学习经验失败: " + e.getMessage()));
        }
    }

    /**
     * 创建知识
     */
    @PostMapping("/knowledge/{lifeEntityId}")
    @Operation(summary = "创建知识", description = "为生命体创建新的知识")
    public ResponseEntity<ApiResponse<KnowledgeBase>> createKnowledge(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "知识数据") @RequestBody Map<String, Object> knowledgeData) {
        
        try {
            KnowledgeBase knowledge = knowledgeManagementService.createKnowledge(lifeEntityId, knowledgeData);
            
            return ResponseEntity.ok(ApiResponse.success(knowledge));
            
        } catch (Exception e) {
            log.error("创建知识失败", e);
            return ResponseEntity.ok(ApiResponse.error("创建知识失败: " + e.getMessage()));
        }
    }

    /**
     * 搜索知识
     */
    @GetMapping("/knowledge/search/{lifeEntityId}")
    @Operation(summary = "搜索知识", description = "搜索指定生命体的知识")
    public ResponseEntity<ApiResponse<List<KnowledgeBase>>> searchKnowledge(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        
        try {
            List<KnowledgeBase> knowledge = knowledgeManagementService
                    .searchKnowledge(lifeEntityId, keyword, null);
            
            return ResponseEntity.ok(ApiResponse.success(knowledge));
            
        } catch (Exception e) {
            log.error("搜索知识失败", e);
            return ResponseEntity.ok(ApiResponse.error("搜索知识失败: " + e.getMessage()));
        }
    }

    /**
     * 获取知识库
     */
    @GetMapping("/knowledge/{lifeEntityId}")
    @Operation(summary = "获取知识库", description = "获取指定生命体的知识库")
    public ResponseEntity<ApiResponse<Page<KnowledgeBase>>> getKnowledgeBase(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size) {
        
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            Page<KnowledgeBase> knowledge = knowledgeBaseRepository.findByLifeEntityId(lifeEntityId, pageable);
            
            return ResponseEntity.ok(ApiResponse.success(knowledge));
            
        } catch (Exception e) {
            log.error("获取知识库失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取知识库失败: " + e.getMessage()));
        }
    }

    /**
     * 验证知识
     */
    @PutMapping("/knowledge/{knowledgeId}/validate")
    @Operation(summary = "验证知识", description = "验证指定的知识")
    public ResponseEntity<ApiResponse<String>> validateKnowledge(
            @Parameter(description = "知识ID") @PathVariable Long knowledgeId,
            @Parameter(description = "是否有效") @RequestParam boolean isValid,
            @Parameter(description = "验证原因") @RequestParam(required = false) String reason) {
        
        try {
            knowledgeManagementService.validateKnowledge(knowledgeId, isValid, reason);
            
            return ResponseEntity.ok(ApiResponse.success("知识验证完成"));
            
        } catch (Exception e) {
            log.error("验证知识失败", e);
            return ResponseEntity.ok(ApiResponse.error("验证知识失败: " + e.getMessage()));
        }
    }

    /**
     * 应用知识
     */
    @PostMapping("/knowledge/{knowledgeId}/apply")
    @Operation(summary = "应用知识", description = "应用指定的知识")
    public ResponseEntity<ApiResponse<KnowledgeManagementService.KnowledgeApplication>> applyKnowledge(
            @Parameter(description = "知识ID") @PathVariable Long knowledgeId,
            @Parameter(description = "应用上下文") @RequestBody Map<String, Object> applicationContext) {
        
        try {
            KnowledgeManagementService.KnowledgeApplication result = 
                    knowledgeManagementService.applyKnowledge(knowledgeId, applicationContext);
            
            return ResponseEntity.ok(ApiResponse.success(result));
            
        } catch (Exception e) {
            log.error("应用知识失败", e);
            return ResponseEntity.ok(ApiResponse.error("应用知识失败: " + e.getMessage()));
        }
    }

    /**
     * 获取学习洞察
     */
    @GetMapping("/insights/{lifeEntityId}")
    @Operation(summary = "获取学习洞察", description = "获取生命体的学习洞察")
    public ResponseEntity<ApiResponse<ExperienceLearningService.LearningInsights>> getLearningInsights(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId) {
        
        try {
            ExperienceLearningService.LearningInsights insights = 
                    experienceLearningService.learnFromHistory(lifeEntityId);
            
            return ResponseEntity.ok(ApiResponse.success(insights));
            
        } catch (Exception e) {
            log.error("获取学习洞察失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取学习洞察失败: " + e.getMessage()));
        }
    }

    /**
     * 获取统计信息
     */
    @GetMapping("/statistics/{lifeEntityId}")
    @Operation(summary = "获取统计信息", description = "获取学习和适应的统计信息")
    public ResponseEntity<ApiResponse<LearningAdaptationService.LearningAdaptationStatistics>> getStatistics(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId) {
        
        try {
            LearningAdaptationService.LearningAdaptationStatistics statistics = 
                    learningAdaptationService.getStatistics(lifeEntityId);
            
            return ResponseEntity.ok(ApiResponse.success(statistics));
            
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取统计信息失败: " + e.getMessage()));
        }
    }

    /**
     * 维护知识库
     */
    @PostMapping("/knowledge/maintain/{lifeEntityId}")
    @Operation(summary = "维护知识库", description = "维护指定生命体的知识库")
    public ResponseEntity<ApiResponse<KnowledgeManagementService.KnowledgeMaintenanceResult>> maintainKnowledgeBase(
            @Parameter(description = "生命体ID") @PathVariable Long lifeEntityId) {
        
        try {
            KnowledgeManagementService.KnowledgeMaintenanceResult result = 
                    knowledgeManagementService.maintainKnowledgeBase(lifeEntityId);
            
            return ResponseEntity.ok(ApiResponse.success(result));
            
        } catch (Exception e) {
            log.error("维护知识库失败", e);
            return ResponseEntity.ok(ApiResponse.error("维护知识库失败: " + e.getMessage()));
        }
    }
}